import java.util.PriorityQueue;
import java.util.Timer;

class MyTimerTask implements Comparable<MyTimerTask>{

    private long time;
    private Runnable runnable;
    public MyTimerTask(Runnable runnable,long delay){
        time = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public void schedule(Runnable runnable, long delay){
        synchronized (locker){
            MyTimerTask task = new MyTimerTask(runnable,delay);
            queue.offer(task);
            locker.notify();
        }
    }
    //扫描线程
    public MyTimer(){
        Thread t = new Thread(() -> {
            //最外层循环用来扫描
            while (true){
                try {
                    //此时的while主要是跟据wait搭配
                    while (queue.isEmpty()){
                        //此时队列为空,不应该取元素
                        //使用wait等待优于使用continue,continue会导致无限循环,增大cpu开销
                        locker.wait();
                    }
                    MyTimerTask task = queue.peek();
                    long curTime = System.currentTimeMillis();
                    if(curTime > task.getTime()){
                        //说明该执行任务了
                        queue.poll();
                        task.getRunnable().run();
                        //调用run方法执行任务
                    }else {
                        locker.wait(task.getTime()-curTime);
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Demo13 {
}
